<?php

namespace App\Console\Commands;

use App\Models\Pinpai;
use App\Models\Industry;
use App\Models\Brand;
use Illuminate\Console\Command;

class ReorganizeBrand extends Command {
    
    protected $signature = 'rb';
    protected $description = 'ReorganizeBrand';
    
    public function __construct() {
        parent::__construct ();
    }
    
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function handle() {
        $this->error('开始整理品牌数据');
        $industries = Industry::select('id', 'name')->get();
        foreach ($industries as $industry) {
            $brands = Pinpai::select('title', 'zongtouzi')->where('hangye', $industry->name)->where('zongtouzi', '>', 0)->get();
            $this->saveBrand($brands, $industry);
            unset($brands);
        }
    }
    
    public function saveBrand($brands, $c) {
        $i = 1;
        $count = count($brands);
        foreach ($brands as $brand) {
            $brand->title = $this->formatName($brand->title, '加盟');
            $b = Brand::where('industry_id', $c->id)->where('name', $brand->title)->first();
            if(is_null($b)) {
                $b = new Brand;
                $b->industry_id = $c->id;
                $b->name = $brand->title;
                $b->oldprice = $brand->zongtouzi;
                $b->price = $brand->zongtouzi - (rand(10, 29) * 0.01);
                $b->save();
                $this->info('行业：'.$c->name.':'.'品牌：'.$i.'/'.$count.'  '.$b->name);
            }
            $i++;
            unset($b);
            unset($brand);
        }
    }
    
    public function formatName($name, $keyword) {
        $nameFormat = str_replace($keyword, "", $name);
        return $nameFormat;
    }
}
